const app = getApp()
const { processListImages } = require('../../utils/image')
const request = require('../../utils/request.js');
Page({
  data: {
    supplyList: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    keyword: '',
    type: '',
    status: '在售',
    minPrice: '',
    maxPrice: ''
  },

  onLoad: function () {
    this.loadSupplyList()
  },

  onShow: function() {
    if (app.globalData.needRefresh) {
      this.setData({
        page: 1,
        hasMore: true,
        supplyList: []
      })
      // 重新请求列表数据
      setTimeout(() => {
        this.loadSupplyList();
      },1500)
      // 重置标志位
      app.globalData.needRefresh = false;
    }
  },

  onPullDownRefresh: function () {
    this.setData({
      page: 1,
      hasMore: true,
      supplyList: []
    })
    this.loadSupplyList().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  onReachBottom: function () {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreSupplyList()
      this.setData({ loading: true })
    }
  },

  // 加载供应列表
  loadSupplyList: function () {
    return new Promise((resolve, reject) => {
      // 构建请求参数
      const params = {
        page: this.data.page,
        pageSize: this.data.pageSize,
        keyword: this.data.keyword,
        type: this.data.type,
        status: this.data.status
      }
      
      // 只有当价格区间有值时才添加到参数中
      if (this.data.minPrice !== '') {
        params.minPrice = this.data.minPrice
      }
      
      if (this.data.maxPrice !== '') {
        params.maxPrice = this.data.maxPrice
      }
      
      request.request({
        url: `${app.globalData.baseUrl}/api/residues`,
        method: 'GET',
        data: params,
        header: {
          'Authorization': `Bearer ${app.getGlobalToken()}`
        },
        success: (res) => {
          const { list, total } = res.data.data

          // 使用工具函数处理图片URL
          const processedList = processListImages(list)

          this.setData({
            supplyList: [...this.data.supplyList, ...processedList],
            hasMore: this.data.supplyList.length + processedList.length < total
          })
          resolve()
        },
        fail: reject
      })
    })
  },

  // 加载更多供应列表
  loadMoreSupplyList: function () {
    this.setData({
      page: this.data.page + 1
    })
    this.loadSupplyList().then(() => {
      this.setData({ loading: false })
    })
  },

  // 切换分类
  switchCategory: function (e) {
    const category = e.currentTarget.dataset.category
    this.setData({
      type: category,
      page: 1,
      hasMore: true,
      supplyList: []
    })
    this.loadSupplyList()
  },

  // 搜索
  onSearch: function (e) {
    const keyword = e.detail.value || ''
    this.setData({
      keyword: keyword,
      page: 1,
      hasMore: true,
      supplyList: []
    })
    this.loadSupplyList()
  },

  // 跳转到详情页
  goToDetail: function (e) {
    const id = e.currentTarget.dataset.id
    request.request({
      url: `${app.globalData.baseUrl}/api/view-records`,
      method: 'POST',
      data: {
        productId: id
      },
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        if(res.data.code === 200) {
            console.log('新增足迹成功')
        }
      },
    })
    wx.navigateTo({
      url: `/pages/supply/detail/detail?id=${id}`
    })
  },

  // 跳转到发布页
  goToPublish: function () {
    wx.navigateTo({
      url: '/pages/supply/publish/publish'
    })
  },

  // 处理最低价格输入
  onMinPrice: function(e) {
    let minPrice = e.detail.value
    
    // 验证输入是否为有效数字
    if (minPrice && isNaN(parseInt(minPrice))) {
      wx.showToast({
        title: '请输入有效数字',
        icon: 'none'
      })
      return
    }
    
    // 转换为数字
    minPrice = minPrice ? parseInt(minPrice) : ''
    
    // 验证最低价不能大于最高价
    if (minPrice && this.data.maxPrice && minPrice > this.data.maxPrice) {
      wx.showToast({
        title: '最低价不能大于最高价',
        icon: 'none'
      })
      return
    }
    
    this.setData({
      minPrice: minPrice,
      page: 1,
      hasMore: true,
      supplyList: []
    })
    this.loadSupplyList()
  },

  // 处理最高价格输入
  onMaxPrice: function(e) {
    let maxPrice = e.detail.value
    
    // 验证输入是否为有效数字
    if (maxPrice && isNaN(parseInt(maxPrice))) {
      wx.showToast({
        title: '请输入有效数字',
        icon: 'none'
      })
      return
    }
    
    // 转换为数字
    maxPrice = maxPrice ? parseInt(maxPrice) : ''
    
    // 验证最高价不能小于最低价
    if (maxPrice && this.data.minPrice && maxPrice < this.data.minPrice) {
      wx.showToast({
        title: '最高价不能小于最低价',
        icon: 'none'
      })
      return
    }
    
    this.setData({
      maxPrice: maxPrice,
      page: 1,
      hasMore: true,
      supplyList: []
    })
    this.loadSupplyList()
  }
}) 